package aaa0proxy;

import java.io.*;
import java.net.*;

import log.Log;

import com.attilax.exception.ExUtil;
import com.attilax.json.AtiJson;
import com.attilax.net.SocketUtil;
import com.attilax.web.UrlX;

public class MyHttpProxy extends Thread {
	static public int CONNECT_RETRIES = 5; // 尝试与目标主机连接次数
	static public int CONNECT_PAUSE = 5; // 每次建立连接的间隔时间
	static public int TIMEOUT = 20000; // 每次尝试连接的最大时间

	static public boolean logging = false; // 是否记录日志


	// 与客户端相连的Socket
	protected Socket csocket;

	public MyHttpProxy(Socket cs) {
		csocket = cs;
		start();//run ()
	}



	public void run() {
		String reqHead_firstLine = ""; // 读取请求头
		String URL = ""; // 读取请求URL
		String host = ""; // 读取目标主机host
		int port = 80; // 默认端口80
		Socket ssocket = null;
		SocketUtil client_SocketUtil=null;
		SocketUtil server_SocketUtil_remote = null;
		Log logger=new Log();
		System.out.println("--log file:"+logger.LOGFILENAME_C );
		try {
			  client_SocketUtil=new SocketUtil(csocket).setSoTimeout(TIMEOUT).setLogger(logger);
		
		 
			UrlX urlUtil=new UrlX();
			try {
				reqHead_firstLine = client_SocketUtil. readFirstLine().firstLine;
			} catch (Exception e) {
				 System.out.println("---read first line ex,msg:"+e.getMessage());
				 	//	、、+ "csocket inso:"+ AtiJson.toJson(csocket) );
				ExUtil.throwEx(e);
			}
		
			
			if(reqHead_firstLine.contains(".jpg"))
				System.out.println("dbg");
		 
			// 抽取URL(<a href="http://www.baidu.com/">http://www.baidu.com/</a>)
			//GET http://s.cimg.163.com/catchpic/E/E0/E007CE953D48E9E1EC2319B343B5940D.jpg.670x270.jpg HTTP/1.1
			URL = urlUtil.getRequestURL(reqHead_firstLine);
			System.out.println("--url："+URL);
			if(URL.contains("1366134690"))
				System.out.println("dbg");

			
			host = urlUtil.hostNoport(URL);
			port=urlUtil.port(URL);
		//	s.cimg.163.com

		
			  server_SocketUtil_remote=	new SocketUtil()
					.createConn2remote(host, port, CONNECT_RETRIES,
							CONNECT_PAUSE).setSoTimeout(TIMEOUT).setLogger(logger)
					.write(reqHead_firstLine+"").write(client_SocketUtil.charFirstLineBreak);
 
			 
			server_SocketUtil_remote.pipe(client_SocketUtil.is,  client_SocketUtil.os); // 建立通信管道;	 
			 
			
			
				
			 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		 	new SocketUtil(  client_SocketUtil).close();
		 	new SocketUtil(  server_SocketUtil_remote) .close();
		 	logger.flush();logger.close();
		 	System.out.println("--thd finish");
		}
	}

	
	
	

	

	

	public static void startProxy(int port, Class clobj) {
		try {
			ServerSocket ssock = new ServerSocket(port);  //if port use ,throw ex
			/*
			 * java.net.BindException: Address already in use: JVM_Bind
			 * */
			System.out.println("---start ok port:"+port);
			while (true) {
				Class[] sarg = new Class[1];
				Object[] arg = new Object[1];
				sarg[0] = Socket.class;
				try {
					java.lang.reflect.Constructor cons = clobj
							.getDeclaredConstructor(sarg);
					arg[0] = ssock.accept();
					cons.newInstance(arg); // 创建HttpProxy或其派生类的实例
				} catch (Exception e) {
					Socket esock = (Socket) arg[0];
					try {
						esock.close();
					} catch (Exception ec) {
					}
				}
			}
		} catch (IOException e) {
			System.out.println("\nStartProxy Exception:");
			e.printStackTrace();
		}
	
	}

	// 测试用的简单main方法
	static public void main(String args[]) throws FileNotFoundException {
		System.out.println("在端口808启动代理服务器\n");

//		MyHttpProxy.log_S = file_S;
//		MyHttpProxy.log_C = file_C;
//		MyHttpProxy.logging = true;
		MyHttpProxy.startProxy(808, MyHttpProxy.class);
	}
}